<template>
  <div class='img'>
    <a-upload
      name='file'
      accept='.png,.jpg,.jpeg'
      listType='picture-card'
      :multiple='isMultiple'
      :action='uploadAction'
      :headers='headers'
      :data='{biz:bizPath}'
      :fileList='fileList'
      :beforeUpload='beforeUpload'
      :disabled='disabled'
      :isMultiple='isMultiple'
      :showUploadList='isMultiple'
      @change='handleChange'
      @preview='handlePreview'
>
      <img v-if='!isMultiple && picUrl' :src='getAvatarView()' style='height:102px;max-width:300px' />
      <div v-else>
        <a-icon :type="uploadLoading ? 'loading' : 'plus'" />
        <div class='ant-upload-text'>{{ text }}</div>
      </div>
    </a-upload>
    <a-modal :visible='previewVisible' :footer='null' @cancel='handleCancel'>
      <img alt='example' style='width: 100%' :src='previewImage' />
    </a-modal>
  </div>
</template>

<script>
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { getFileAccessHttpUrl } from '@/api/manage'

const uidGenerator = () => {
  return '-' + parseInt(Math.random() * 10000 + 1, 10)
}
const getFileName = (path) => {
  if (path.lastIndexOf('\\') >= 0) {
    let reg = new RegExp('\\\\', 'g')
    path = path.replace(reg, '/')
  }
  return path.substring(path.lastIndexOf('/') + 1)
}
export default {
  name: 'JImageUpload',
  data() {
    return {
      uploadAction: window._CONFIG['domianUploadURL'] + '/cnUploadController/uploadOss',
      uploadLoading: false,
      picUrl: false,
      headers: {},
      fileList: [],
      previewImage: '',
      previewVisible: false
    }
  },
  props: {
    text: {
      type: String,
      required: false,
      default: '上传'
    },
    /*这个属性用于控制文件上传的业务路径*/
    bizPath: {
      type: String,
      required: false,
      default: 'jpg'
    },
    value: {
      type: [String, Array],
      required: false
    },
    disabled: {
      type: Boolean,
      required: false,
      default: false
    },
    isMultiple: {
      type: Boolean,
      required: false,
      default: false
    }
  },
  watch: {
    value(val) {
      console.log(val, 'val')
      if (val instanceof Array) {
        this.initFileList(val.join(','))
      } else {
        this.initFileList(val)
      }
      if (!val || val.length == 0) {
        this.picUrl = false
      }
    }
  },
  created() {
    const token = Vue.ls.get(ACCESS_TOKEN)
    this.headers = {
      'Authorization': 'Bearer ' + token.access_token
      // 'Authorization':token.loginUserToken
      // 'loginUserToken':token.loginUserToken

    }
  },
  methods: {
    initFileList(paths) {
      if (!paths || paths.length == 0) {
        this.fileList = []
        return
      }
      this.picUrl = true
      let fileList = []
      let arr = paths.split(',')
      for (var a = 0; a < arr.length; a++) {
        let url = getFileAccessHttpUrl(arr[a])
        fileList.push({
          uid: uidGenerator(),
          name: getFileName(arr[a]),
          status: 'done',
          url: url,
          response: {
            status: 'history',
            message: arr[a]
          }
        })
      }
      this.fileList = fileList
    },

    beforeUpload: function(file) {
      var size = file.size
      if (size != undefined && size > (2 * 1024 * 1000)) {
        this.$message.warning('文件不能超过2Mb!')
        file.status = 'toolager'
        return false
      }
      var fileType = file.type
      if (fileType.indexOf('image') < 0) {
        this.$message.warning('请上传图片')
        return false
      }
    },
    handleChange(info) {
      this.picUrl = false
      let fileList = []
      if (info.file.status === 'uploading') {
        fileList = info.fileList
      }
      if (info.file.status === 'done') {
        if (info.file.response.success) {
          fileList = info.fileList
          this.picUrl = true
          fileList = fileList.map((file) => {
            if (file.response) {
              if (file.response.status === 'history') {
                file.url = file.response.message
              } else if (info.file.status === 'done') {
                if (file.response.result) {
                  file.url = file.response.result.url
                }
              }
            }
            return file
          })
        } else {
          this.handleDelete(info.file)
          info.file.status = 'error'  //标记失败
          this.$message.error(`${info.file.name} 上传失败.`)
        }
        //this.$message.success(`${info.file.name} 上传成功!`);
      } else if (info.file.status === 'error') {
        this.$message.error(`${info.file.name} 上传失败.`)
        this.handleDelete(info.file)
      } else if (info.file.status === 'removed') {
        this.handleDelete(info.file)
      }
      if (!(info.file.status === 'toolager'
        || info.file.status === 'error'
        || info.file.status === 'removed'
        || info.file.status == undefined)) {
        this.fileList = fileList
      }
      if (info.file.status === 'done' || info.file.status === 'removed') {
        if (info.file.status === 'history' || (info.file.response && info.file.response.success)) {
          this.handlePathChange()
        }
      }
    },
    // 预览
    handlePreview(file) {
      this.previewImage = file.url || file.thumbUrl
      this.previewVisible = true
    },
    getAvatarView() {
      if (this.fileList.length > 0) {
        let url = this.fileList[0].url
        return getFileAccessHttpUrl(url)
      }
    },
    handlePathChange() {
      const uploadFiles = this.fileList
      let path
      if (!uploadFiles || uploadFiles.length == 0) {
        path = ''
      }
      let arr = []
      if (!this.isMultiple) {
        arr.push(uploadFiles[uploadFiles.length - 1].response.result.url)
        path = arr.join(',')
      } else {
        for (var a = 0; a < uploadFiles.length; a++) {
          arr.push(uploadFiles[a].url || uploadFiles[a].message)
          // arr = [
          // 	...arr,
          // 	...(uploadFiles[a].response && uploadFiles[a].response.result
          // 		? uploadFiles[a].response.result.map((img) => img.url)
          // 		: []),
          // ]
        }
        path = arr
      }
      this.$emit('change', path)
    },
    handleDelete(file_) {
      let index = this.fileList.findIndex((file) => file.uid === file_.uid)
      //如有需要新增 删除逻辑
      this.fileList.splice(
        index, 1
      )
    },
    handleCancel() {
      this.close()
      this.previewVisible = false
    },
    close() {
    }
  },
  model: {
    prop: 'value',
    event: 'change'
  }
}
</script>

<style scoped>
/deep/ .ant-upload.ant-upload-select-picture-card {
  width: 120px;
  height: 120px;
  box-sizing: border-box;
}

/deep/ .imgupload .iconp {
  padding: 20px;
}

/* update--end--autor:lvdandan-----date:20201016------for：j-image-upload图片组件单张图片详情回显空白*/

/deep/ .image-upload-single-over .ant-upload-select {
  display: none
}
</style>
